<?php
/**
 * 订单数据处理事件接口
 * @author Max.Yu <max@jipu.com>
 */

namespace Admin\Event;

class OrderEvent extends \Think\Controller{

  /**
   * 获取分页列表
   */
  public function getPageList($where = array()){
    $where = array(
      'groupby' => 'payment_id',
      'status' => array('egt', 1)
    );
    //订单状态过滤
    $o_status = I('get.o_status', -2);
    if($o_status > -2){
      $where['o_status'] = array('eq', $o_status);
      
    }elseif($o_status == -3){
      $where['payment_time'] = array('gt', 0);
    }
    $this->o_status = $o_status;
    
    //用户ID过滤
    $uid = I('get.uid', 0);
    if($uid > 0){
      $where['uid'] = $uid;
    }
    //分销过滤
    $sdp_uid = I('get.sdp_uid', 0);
    if(1 == I('is_sdp', 0)){
      $where['sdp_uid'] = array('gt', 0);
    }
    /*if($sdp_uid > 0){
      $where['sdp_uid'] = $sdp_uid;
      $this->sdp_uid = $sdp_uid;
    }*/
    if($sdp_uid > 0){
        //如果存在分销店铺id，只查询这个分销店铺相关的订单
        $status = M('sdpRecord')->where("sdp_uid='{$sdp_uid}'")->field('order_id')->select();
        if(is_array($status) && !empty($status)){
            $data = array();
            foreach($status as $val){
                $data[] = $val['order_id'];
            }
            $where['id'] = array('in',$data);
            $this->sdp_uid = $sdp_uid;
        }
    }
    //供应商过滤
    if(IS_SUPPLIER){
      $where['supplier_ids'] = UID;
      $where['payment_time'] = array('gt', 0);
    }
    //时间过滤
    $time_type = I('get.time_type', null);
    $start_time = I('get.start_time', '');
    $end_time = I('get.end_time', '');
    if(isset($time_type) && in_array($time_type, array('create_time', 'payment_time'))){
      $start_time = !empty($start_time) ? strtotime($start_time) : '';
      $end_time = !empty($end_time) ? strtotime($end_time) + 24 * 3600 : '';
      if(!empty($start_time)){
        $where[] = "`$time_type` > $start_time";
      }
      if(!empty($end_time)){
        $where[] = "`$time_type` < $end_time";
      }
      if($time_type == 'payment_time' && ($start_time + $end_time) > 0){
        $where['payment_time'] = array('gt', 0);
      }
      $this->time_type = $time_type;
    }
      $store = I('request.store');
      if($store){
          $store_where['store_name'] = array('like','%'.$store.'%');
          $store_ids = M('Store')->where($store_where)->getField('store_id',true);
          if(!$store_ids)$store_ids=array(0);
          if($store_ids)$where['store_ids'] = array('IN',array_unique($store_ids));
      }
    //字符串过滤
    $keywords = I('get.keywords', '', trim);
    if(!empty($keywords)){
      $where['order_sn'] = array('like', '%'.$keywords.'%');
      $this->keywords = $keywords;
    }
    //按条件查询结果并分页
    $list = array();
    C('LIST_ROWS', 10);
    //收货人名字或者手机搜索
    $ship = I('get.ship');
    if($ship){
      $ship_where['ship_uname|ship_mobile'] = array('like', '%'.$ship.'%');
      $ship_payment_ids = M('OrderShip')->where($ship_where)->getField('payment_id', true);
      if(empty($ship_payment_ids)){
        return false;
      } 
      $where['payment_id'] = array('IN', array_unique($ship_payment_ids));
    }
    $order = (-3 == $o_status) ? 'payment_time desc, id desc' : 'id desc';
    if(I('order_type' , 'int' ,0) > 0){
         $map['order_type'] = $where['order_type'] = I('order_type' );
         $this->order_type  = I('order_type' );
      }
    $payment_list = A('Home/Page', 'Event')->lists('Order', $where, $order, 10, array(), 'payment_id');
    if($payment_list){
      $payment_ids = array_column($payment_list, 'payment_id');
      $map = array(
        'payment_id' => array('IN', array_unique($payment_ids)),
        'status' => array('egt', 1)
      );
      //供应商过滤
      if(IS_SUPPLIER){
        $map['supplier_ids'] = UID;
      }
      $list = M('Order')->field('*')->where($map)->order('field(payment_id,'.implode(',', $payment_ids).')')->select();
    }
    return $list;
  }

  /**
   * 订单数据按支付单号分组
   */
  public function orderFormat($order_list){
    //空数据直接返回
    if(empty($order_list)){
      return array();
    }
    $list = array();
    foreach($order_list as $order){
      $payment_id = $order['payment_id'];
      if(!isset($list[$payment_id])){
        $list[$payment_id] = array(
          'num' => 0,
          'is_sdp' => $order['sdp_uid'] != 0,
          'invoice_need' => $order['invoice_need'],
          'payment' => M('Payment')->field('uid, payment_sn, payment_status, payment_type, payment_amount, finance_amount, create_time')->getById($payment_id),
          'ship' => M('OrderShip')->getByPaymentId($payment_id),
        );
      }
      $order['item_ids_arr'] = explode(',', $order['item_ids']);
      $list[$payment_id]['order'][$order['id']] = $order;
      //店铺分类
      $order['item_store_arr'] = explode(',',$order['store_ids']);
      foreach ($order['item_store_arr'] as $key => $value) {
        $store_order = M('StoreOrder')->where(array('order_sn'=>$order['order_sn'],'store_ids'=>$value))->find();
        $store_order['item_ids_arr'] = M('OrderItem')->where(array('store_id'=>$value,'order_id'=>$order['id']))->getField('item_id',true);
        $store_order['old_order_id'] = $order['id'];
        $list[$payment_id]['store_order'][$value] = $store_order;
      }
      $list[$payment_id]['num'] = count($list[$payment_id]['order']);
    }
    //dump($list);
    return $list;
  }

  /**
   * 订单数据根据商户进行处理
   * @author buddha <[email address]>
   * @return [type] [description]
   */
  public function storeOrderFormat($info){

    //店铺ID
    $store_id = $info['store_ids'];

    $list = M('Order')->where(array('order_sn'=>$info['order_sn']))->find();

    //获取支付表信息
    $payment = M('Payment')->where(array('id'=>$list['payment_id']))->find();

    $info['order_total_amount'] = (float)$list['total_amount'];

    //优惠券
    $store_coupons = unserialize($list['store_coupons']);

    //额外数据
    $store_other = unserialize($list['store_other']);

    //优惠券使用情况
    if ($store_coupons['store_coupon_use'][$store_id] > 0) {
      
      $info['is_use_coupon'] = 1;

      $info['coupon_amount'] = $store_coupons['store_coupon_val'][$store_id];

    }
    //店铺合计金额
    foreach ($store_other['store_amount'] as $key => $value) {
      
      $order_total += $value; 

    }

    //添加判断 余额
    $new_finance_amount = M('StoreOrder')->where('order_sn='.$info['order_sn'])->sum('finance_amount');

    if ($payment['finance_amount'] != $new_finance_amount) {
        foreach ($store_other['store_amount'] as $key => $value) {
            $new_finance = sprintf("%.2f", ($payment['finance_amount'] * $value / $order_total));
            $map = array(
                  'store_ids'      => $key,
                  'order_sn'       => $info['order_sn']
              );
          M('StoreOrder')->where($map)->setField('finance_amount',$new_finance);
        }
        $maps = array(
            'store_ids' => $info['store_ids'],
            'order_sn'  => $info['order_sn']
          );
        $new_total_amount = M('StoreOrder')->where($maps)->getField('total_amount');
    }else{
        $new_total_amount = $info['total_amount'];
    }

    //余额使用情况 分配
    $finance_amount = $payment['finance_amount'] * $new_total_amount / $order_total;

    $info['finance_amount'] = ($finance_amount * 1000 < 0.01) ? 0 : round($finance_amount,2);

    //积分使用情况 分配
    $score_amount = $payment['score_amount'] * $info['total_amount'] / $order_total;

    $info['score_amount'] = ($score_amount * 1000 < 0.01) ? 0 : round($score_amount,2);

    //礼品卡使用情况 分配
    $card_amount = $payment['card_amount'] * $info['total_amount'] / $order_total;

    $info['card_amount'] = ($card_amount * 1000 < 0.01) ? 0 : round($card_amount,2);

    //满减金额
    $info['manjian'] = $store_other['store_manjian'][$store_id];

    if ($info['card_amount'] > 0) {
      $info['is_use_card'] = 1;
    }

    //运费情况
    $info['delivery_fee'] = $store_other['store_freight'][$store_id];

    //三方支付金额
    if ($payment['payment_amount'] > 0) {
      $info['online_amount'] = sprintf('%.2f',($info['total_amount'] - ($info['card_amount'] + $info['finance_amount'] + $info['score_amount'])));
    }else{
      $info['online_amount'] = 0;
    }

    //优惠金额 商户自己的优惠
    $info['discount_amount'] = sprintf("%.2f", ($info['total_price'] + $info['delivery_fee'] - $info['total_amount'] - $info['coupon_amount'] - $info['manjian']));

    return $info;

  }
}
